package com.sali.service.data_entry;

import cn.hutool.core.io.watch.SimpleWatcher;
import cn.hutool.core.io.watch.WatchMonitor;
import cn.hutool.core.io.watch.WatchUtil;
import cn.hutool.core.io.watch.Watcher;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sali.entity.TransferObject;
import com.sali.service.data_file_uploader.refcount.ReferenceManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;

/**
 * @author sali
 * @date 2025/3/16 18:47
 */
public class FileReadListener {

    public static Logger log = LoggerFactory.getLogger(FileReadListener.class);

    private String dataEntryFilePath;

    private BlockingQueue<List<TransferObject>> dataChannel;

    public FileReadListener(String dataEntryFilePath, BlockingQueue<List<TransferObject>> dataChannel) {
        this.dataEntryFilePath = dataEntryFilePath;
        this.dataChannel = dataChannel;
    }

    public void start() {
        // 创建一个文件监听器
        Watcher watcher = new SimpleWatcher() {
            @Override
            public void onCreate(WatchEvent<?> event, Path currentPath) {
                // 当有新文件创建时触发此方法
                Object obj = event.context();
                if (obj instanceof Path) {
                    Path filePath = currentPath.resolve((Path) obj);
                    File newFile = filePath.toFile();

                    // 新建当前源文件的引用计数
                    ReferenceManager.createRefCounter(newFile.getAbsolutePath(), newFile.getName());

                    // 读取新文件的内容
                    long totalCount = readJsonFileLineByLine(newFile);

                    // 扫描完毕
                    ReferenceManager.scanCompleted(newFile.getName(), totalCount);
                }
            }
        };
        // 创建一个文件监控器，监听指定文件夹的文件创建事件
        WatchMonitor monitor = WatchUtil.createAll(dataEntryFilePath, watcher);
        // 启动监控器
        monitor.start();
    }

    private long readJsonFileLineByLine(File file) {
        long totalCount = 0;

        ObjectMapper objectMapper = new ObjectMapper();
        List<TransferObject> transferObjectList = new ArrayList<>();
        if (file.exists() && file.isFile()) {
            try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    try {
                        // 尝试将每行内容解析为 JSON 对象
                        TransferObject transferObject = objectMapper.readValue(line, TransferObject.class);
                        transferObject.setSourceFileId(file.getName());
                        transferObjectList.add(transferObject);
                    } catch (IOException e) {
                        log.error("当前行不是有效的 JSON TransferObject 数据: {}, e", line, e);
                    }
                }
                totalCount = transferObjectList.size();
                dataChannel.put(transferObjectList);
            } catch (IOException | InterruptedException e) {
                System.out.println("读取文件时出错: " + e.getMessage());
            }
        }

        return totalCount;
    }


}
